package wili.graphics;

import java.awt.AWTEvent;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
/**
 * @author weilai345 Jul 25, 2020
 */
public class ScreenCapture_byClick extends JFrame {
	private static final long serialVersionUID = 1L;

	private JPanel contentPane;

	static String LABLE_TXT;

	static JTextField INPUT;

	static File TO_DIR;

	static int TIMES;

	static JButton BUTTON;
	static JPanel addGridLayoutPanel(int rows, int cols, JComponent toComp) {
		JPanel pan = new JPanel(new GridLayout(rows, cols));
		toComp.add(pan);
		return pan;
	}

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					ScreenCapture_byClick frame = new ScreenCapture_byClick();
					frame.setVisible(true);
					frame.setTitle("点击按钮或Ctrl 进行截屏");
					frame.setResizable(false);
					if ("".isEmpty()) {
						Toolkit tk = Toolkit.getDefaultToolkit();
						class ImplAWTEventListener implements AWTEventListener {
							//@Override
							public void eventDispatched(AWTEvent event) {
								if (event.getClass() == KeyEvent.class) {   
									KeyEvent keyEvent = (KeyEvent) event;
									if (keyEvent.getID() == KeyEvent.KEY_PRESSED) {
										if (keyEvent.getKeyCode() == 17) {// 192:`,17:ctrl
											captureScreen(INPUT == null ? "" : INPUT.getText(), TO_DIR, 1);
											BUTTON.setText("截屏 " + TIMES);
										}
									} else if (keyEvent.getID() == KeyEvent.KEY_RELEASED) {
									}
								}
							}
						}
						tk.addAWTEventListener(new ImplAWTEventListener(), AWTEvent.KEY_EVENT_MASK);
						System.out.println("已启动，请见任务栏图标...");
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public ScreenCapture_byClick() {
		int width = 320, high = 160;
		{
			//
			DateFormat dfDirectory = new SimpleDateFormat("yyyyMMdd");
			String st = ScreenCapture_byClick.class.getSimpleName();
			TO_DIR = new File("c:/a/" + st + "" + dfDirectory.format(new Date()));
			if (!TO_DIR.exists()) {
				TO_DIR.mkdirs();
			}
			// st = "Save Screen capture to dir:\n " + toDir.getAbsolutePath() + "\nMax pic
			// number=1000";
			LABLE_TXT = "<html>截屏保存目录:<br> " + TO_DIR.getAbsolutePath() + "</html>";
		}
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
		setBounds(50, dim.height - high, width, high);
		//
		if (Boolean.FALSE) {
			JMenuBar menuBar = new JMenuBar();
			setJMenuBar(menuBar);
			JMenu menu = new JMenu("aaaaaaaaa");
			menuBar.add(menu);
			//
			JMenuItem menuItem = new JMenuItem("bbbbbbbb");
			menuItem.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					// emo.getInstance();
				}
			});
			menu.add(menuItem);
			JMenuItem menuItem_1 = new JMenuItem("cccccccccc");
			menu.add(menuItem_1);
		}
		contentPane = new JPanel();
		// contentPane.setToolTipText("jjjjjjjjjjjjj");
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new GridLayout(2, 1));
		// contentPane.setLayout(new FlowLayout());
		{
			BUTTON = new JButton("截屏 " + TIMES);
			BUTTON.setFont(new Font("宋体", Font.BOLD, 30));
			contentPane.add(BUTTON);
		}
		JPanel pan = new JPanel();
		{
			contentPane.add(pan);
		}
		{
			pan.setLayout(new GridLayout(2, 1));
			JPanel pan1 = addGridLayoutPanel(1, 2, pan);
			pan1.add(new JLabel("文件名前缀："));
			INPUT = new JTextField(8);
			pan1.add(INPUT, -1);
			{
				int fn = TO_DIR.listFiles().length;
				if (fn > 0) {
					INPUT.setText((fn + 1) + "_");
				}
			}
		}
		{
			pan.add(new JLabel(LABLE_TXT));
			pan.setSize(width, 20);
			pan.setPreferredSize(new Dimension(width, 20));
		}
		contentPane.setVisible(true);
		setContentPane(contentPane);
		BUTTON.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				captureScreen(INPUT == null ? "" : INPUT.getText(), TO_DIR, 1);;
				BUTTON.setText("截屏 " + TIMES);
			}
		});
	}
	static Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();

	static DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
	static void captureScreen(String prefix, File toDir, int printMsg) {
		if (prefix.isEmpty())
			System.out.println();
		File imageFile = new File(toDir, (prefix + (1 + TIMES) + ".png"));
		if ("".isEmpty() && imageFile.exists()) {
			JOptionPane.showConfirmDialog(null, "文件" + imageFile.getName() + " 已存在，请手动处理!", "",
					JOptionPane.DEFAULT_OPTION);
			return;
		}
		++TIMES;
		BufferedImage curImg;
		try {
			curImg = new Robot().createScreenCapture(new Rectangle(dimension));
			ImageIO.write(curImg, "png", imageFile);
			if (printMsg == 1)
				System.out.println("save to:" + imageFile.getAbsolutePath());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
